package com.android.jblm.commandcentral;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;

import com.android.jblm.commandcentral.generators.DirectoryBuilder;
import com.android.jblm.commandcentral.objects.Category;
import com.android.jblm.commandcentral.objects.Contact;
import com.android.jblm.commandcentral.objects.Directory;
import com.android.jblm.commandcentral.objects.Header;

import java.util.HashMap;


public class PhoneBookActivity extends FragmentActivity implements
        HeaderListFragment.OnHeaderSelectedListener,
        SubHeaderFragment.OnSubHeaderSelectedListener,
        ContactListFragment.OnContactSelectedListener,
        ContactFragment.getContactListener{

    private DirectoryBuilder builder;
    private Directory myBook;

    private int selectedHeaderPos = 0;
    private int selectedCategoryPos = 0;
    private int selectedContactPos = 0;

    private  Header[] myHeaders;
    private  Category curCategory;
    private Contact curContact;
    private  HashMap<String, Category[]> myCategories;
    private  HashMap<String, Contact[]> myContacts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_directory);

        Log.w("PhoneBookMain", "checking saved instance");

        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first fragment
        if(findViewById(R.id.fragment_container) != null){

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            builder = new DirectoryBuilder(this);
            setupBook(builder.getBook());

            HeaderListFragment firstFragment = new HeaderListFragment();

            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();


        }

    }

    private void setupBook(Directory theBook) {

        Log.w("PhoneBookMain-setupBook", "-== Setting up main book ==-");
        myBook = theBook;
        myHeaders = myBook.getHeaders();
        myCategories = new HashMap<String, Category[]>();
        myContacts = new HashMap<String, Contact[]>();

        for(Header h: myHeaders){
            Log.w("PhoneBookMain-setupBook", "building header");
            myCategories.put(h.getName(), h.getCategories());
            for(Category c: h.getCategories()){
                Log.w("PhoneBookMain-setupBook", "building category");
                myContacts.put(c.getTitle(), c.getContacts());
            }

        }
    }

    @Override
    public void onHeaderSelected(int position) {
        selectedHeaderPos = position;
        String headerName = myHeaders[position].getName();
        Log.w("PhoneBookActivity", "Header Name " + headerName + " Selected");

        // The user selected the header from the HeaderListFragment


        // Create fragment and give it an argument for the selected article
        SubHeaderFragment newFragment = new SubHeaderFragment();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();


    }

    @Override
    public void onSubHeaderSelected(int position, Category cat) {
        selectedCategoryPos = position;
        curCategory = cat;
        // The user selected the header from the HeaderListFragment

        // Create fragment and give it an argument for the selected article
        ContactListFragment newFragment = new ContactListFragment();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();

    }

    @Override
    public void onContactSelected(Contact c) {
        curContact = c;
    }

    @Override
    public Header[] getMyHeaders() {
        return myHeaders;
    }

    @Override
    public int getSelectedHeaderPos() {
        return selectedHeaderPos;
    }

    public int getSelectedCategoryPos() {
        return selectedCategoryPos;
    }

    public int getSelectedContactPos() {
        return selectedContactPos;
    }

    public Contact getCurContact() {
        return curContact;
    }

    public Category getCurCategory() {
        return curCategory;
    }

    @Override
    public HashMap<String, Category[]> getMyCategories() {
        return myCategories;
    }

    @Override
    public HashMap<String, Contact[]> getMyContacts() {
        return myContacts;
    }




    /**
     * Asynchronous inner class that handles building phone book in separate thread
     * onPostExecute is called when post thread completes, passing the list
     * back to the method setupListView
     */
    class InnerDirectoryBuilder extends AsyncTask<String, Integer, Directory> {


        protected Directory doInBackground(String... params) {

            Log.w("DirectoryBuilder", "building book");
            //builder = new DirectoryBuilder();


            Log.w("DirectoryBuilder", "book built");
            return builder.getBook();
        }

        @Override
        protected void onPostExecute(Directory result){
            Log.w("DirectoryBuilder", "sending book");
            setupBook(result);

        }

        @Override
        protected void onProgressUpdate(Integer... values){

            //Nothing, used to show progress of building book
        }
    }
}
